<template>
  <div class="permission-manage">
    <!-- 左侧菜单树 -->
    <el-card class="menu-tree-card" shadow="hover">
      <template #header>
        <div class="card-header">
          <span class="title">
            <el-icon><Menu /></el-icon>
            菜单结构
          </span>
          <div class="actions">
            <el-button type="primary" @click="handleAddMenu">
              <el-icon><Plus /></el-icon>新增菜单
            </el-button>
          </div>
        </div>
      </template>
      
      <!-- 搜索框 -->
      <div class="tree-search">
        <el-input
          v-model="searchKey"
          placeholder="搜索菜单"
          clearable
          @input="filterNode"
        >
          <template #prefix>
            <el-icon><Search /></el-icon>
          </template>
        </el-input>
      </div>
      
      <el-tree
        ref="menuTreeRef"
        :data="menuList"
        :props="defaultProps"
        node-key="id"
        highlight-current
        :filter-node-method="filterNode"
        :expand-on-click-node="false"
        @node-click="handleNodeClick"
      >
        <template #default="{ node, data }">
          <div class="custom-tree-node">
            <div class="node-content">
              <el-icon>
                <component :is="data.icon || (data.children ? 'Folder' : 'Document')" />
              </el-icon>
              <span class="label">{{ node.label }}</span>
              <el-tag v-if="data.type" size="small" :type="getMenuTagType(data.type)">
                {{ getMenuTypeName(data.type) }}
              </el-tag>
            </div>
            <div class="node-actions">
              <el-button-group>
                <el-button link type="primary" @click.stop="handleAddChild(data)">
                  <el-icon><Plus /></el-icon>
                </el-button>
                <el-button link type="primary" @click.stop="handleEdit(data)">
                  <el-icon><Edit /></el-icon>
                </el-button>
                <el-button 
                  link 
                  type="danger" 
                  :disabled="data.children?.length"
                  @click.stop="handleDelete(data)"
                >
                  <el-icon><Delete /></el-icon>
                </el-button>
              </el-button-group>
            </div>
          </div>
        </template>
      </el-tree>
    </el-card>

    <!-- 右侧详情表单 -->
    <el-card class="menu-form-card" shadow="hover">
      <template #header>
        <div class="card-header">
          <span class="title">
            <el-icon><Setting /></el-icon>
            {{ currentNode ? '菜单配置' : '请选择菜单' }}
          </span>
        </div>
      </template>

      <div class="toolbar">
        <el-button-group>
          <el-button type="primary" @click="handleExport">
            <el-icon><Download /></el-icon>导出配置
          </el-button>
          <el-button type="primary" @click="handleImport">
            <el-icon><Upload /></el-icon>导入配置
          </el-button>
        </el-button-group>
        <el-button-group>
          <el-button type="success" @click="handleExpandAll">
            <el-icon><Expand /></el-icon>展开全部
          </el-button>
          <el-button type="info" @click="handleCollapseAll">
            <el-icon><Fold /></el-icon>折叠全部
          </el-button>
        </el-button-group>
      </div>

      <el-form
        v-if="currentNode"
        ref="formRef"
        :model="formData"
        :rules="formRules"
        label-width="100px"
      >
        <el-form-item label="菜单类型" prop="type">
          <el-radio-group v-model="formData.type">
            <el-radio-button label="menu">菜单</el-radio-button>
            <el-radio-button label="button">按钮</el-radio-button>
            <el-radio-button label="api">接口</el-radio-button>
          </el-radio-group>
        </el-form-item>

        <el-form-item label="菜单名称" prop="title">
          <el-input v-model="formData.title" placeholder="请输入菜单名称" />
        </el-form-item>

        <el-form-item label="权限标识" prop="permission">
          <el-input v-model="formData.permission" placeholder="请输入权限标识">
            <template #append>
              <el-tooltip content="权限标识格式：模块:操作，如：user:create">
                <el-icon><QuestionFilled /></el-icon>
              </el-tooltip>
            </template>
          </el-input>
        </el-form-item>

        <el-form-item v-if="formData.type === 'menu'" label="路由路径" prop="path">
          <el-input v-model="formData.path" placeholder="请输入路由路径" />
        </el-form-item>

        <el-form-item v-if="formData.type === 'menu'" label="图标" prop="icon">
          <el-popover
            v-model:visible="iconSelectVisible"
            placement="bottom-start"
            :width="480"
            trigger="click"
            popper-class="icon-select-popover"
          >
            <template #reference>
              <el-input v-model="formData.icon" placeholder="请选择图标" readonly>
                <template #prefix>
                  <el-icon v-if="formData.icon">
                    <component :is="formData.icon" />
                  </el-icon>
                </template>
                <template #append>
                  <el-icon><Select /></el-icon>
                </template>
              </el-input>
            </template>
            
            <div class="icon-select-container">
              <div class="icon-search">
                <el-input
                  v-model="iconSearchKey"
                  placeholder="搜索图标"
                  clearable
                  size="small"
                >
                  <template #prefix>
                    <el-icon><Search /></el-icon>
                  </template>
                </el-input>
              </div>
              
              <div class="icon-grid">
                <div
                  v-for="icon in filteredIconList"
                  :key="icon.name"
                  class="icon-item"
                  @click="handleIconSelect(icon.name)"
                >
                  <el-icon>
                    <component :is="icon.component" />
                  </el-icon>
                  <span class="icon-name">{{ icon.name }}</span>
                </div>
              </div>
            </div>
          </el-popover>
        </el-form-item>

        <el-form-item label="排序" prop="sort">
          <el-input-number v-model="formData.sort" :min="0" :max="999" />
        </el-form-item>

        <el-form-item label="上级菜单" prop="parentId">
          <el-input
            v-model="formData.parentTitle"
            placeholder="请选择上级菜单"
            readonly
            @click="parentMenuDialogVisible = true"
          >
            <template #append>
              <el-button 
                @click.stop="formData.parentId = null; formData.parentTitle = ''"
                :disabled="!formData.parentId"
              >
                <el-icon><Close /></el-icon>
              </el-button>
            </template>
          </el-input>
        </el-form-item>

        <el-form-item label="状态" prop="status">
          <el-radio-group v-model="formData.status">
            <el-radio-button label="enabled">启用</el-radio-button>
            <el-radio-button label="disabled">禁用</el-radio-button>
          </el-radio-group>
        </el-form-item>

        <el-form-item label="描述" prop="description">
          <el-input
            v-model="formData.description"
            type="textarea"
            :rows="3"
            placeholder="请输入菜单描述"
          />
        </el-form-item>

        <el-form-item label="组件路径" prop="component">
          <el-input v-model="formData.component" placeholder="请输入组件路径">
            <template #append>
              <el-tooltip content="组件路径格式：views/system/user/index">
                <el-icon><QuestionFilled /></el-icon>
              </el-tooltip>
            </template>
          </el-input>
        </el-form-item>

        <el-form-item label="路由配置">
          <el-space>
            <el-switch
              v-model="formData.isCache"
              active-text="开启缓存"
              inactive-text="关闭缓存"
            />
            <el-switch
              v-model="formData.isVisible"
              active-text="显示路由"
              inactive-text="隐藏路由"
            />
          </el-space>
        </el-form-item>

        <el-form-item>
          <el-button type="primary" @click="handleSubmit">保存</el-button>
          <el-button @click="resetForm">重置</el-button>
        </el-form-item>
      </el-form>
      
      <div v-else class="empty-tip">
        <el-empty description="请选择左侧菜单进行配置" />
      </div>
    </el-card>

    <!-- 添加选择上级菜单的对话框 -->
    <el-dialog
      v-model="parentMenuDialogVisible"
      title="选择上级菜单"
      width="30%"
    >
      <el-tree
        :data="menuList"
        :props="defaultProps"
        node-key="id"
        highlight-current
        :expand-on-click-node="false"
        @node-click="handleParentSelect"
      >
        <template #default="{ node, data }">
          <div class="custom-tree-node">
            <div class="node-content">
              <el-icon>
                <component :is="data.icon || (data.children ? 'Folder' : 'Document')" />
              </el-icon>
              <span class="label">{{ node.label }}</span>
            </div>
          </div>
        </template>
      </el-tree>
      <template #footer>
        <el-button @click="parentMenuDialogVisible = false">取消</el-button>
        <el-button type="primary" @click="confirmParentSelect">确定</el-button>
      </template>
    </el-dialog>
  </div>
</template>

<script setup lang="ts">
import { ref, reactive, onMounted, watch, computed } from 'vue'
import { 
  Menu, Plus, Edit, Delete, Setting, Document, Folder,
  QuestionFilled, Select, Search, Close, User, Lock, Key,
  Monitor, Tools, Bell, Message, Link, Position, List,
  Grid, Operation, Tickets, TrendCharts, Histogram,
  PieChart, Briefcase, Notebook, Collection, Guide,
  Management, SetUp, Coin, Money, Wallet, Connection,
  CreditCard, Platform, Switch, Notification, ChatDotRound,
  ChatLineRound, ChatRound, ChatSquare, View, Hide, Star,
  Calendar, Timer, Clock, House, OfficeBuilding, School,
  Reading, Files, Box, Suitcase, Stamp, Discount,
  Goods, ShoppingCart, ShoppingBag, Present, Sell,
  Phone, Cellphone, Camera, Picture, Upload, Download,
  VideoCamera, Film, Headset, Location, Coordinate, Place,
  Promotion, Chicken, Food, Dish, Burger, Mug,
  IceCream, Dessert, Apple, Pear, Orange, Coffee,
  IceTea, Cherry, Watermelon, Grape, RefreshRight,
  Refresh, CircleClose, CircleCheck, Warning, Check, 
  MoreFilled, ArrowDown, ArrowUp, ArrowLeft, ArrowRight,
  Back, Right, Top, Bottom, DCaret, InfoFilled, 
  SuccessFilled, Loading, Failed, Aim, ElementPlus,
  Expand, Fold, FullScreen, Help, HomeFilled, Share,
  StarFilled, UserFilled, Pointer, Rank, ShoppingCartFull,
  Sort, SortDown, SortUp, Stopwatch, Trophy,
  Umbrella, Unlock, WalletFilled, ZoomIn, ZoomOut,
  Opportunity, Shop, ShoppingTrolley, Soccer, Sunny,
  Sunrise, Sunset, TakeawayBox, Ticket, TopLeft,
  TopRight, TurnOff, Van, VideoPause, VideoPlay,
  WarnTriangleFilled, WindPower, Bowl, Brush, BrushFilled,
  CaretBottom, CaretLeft, CaretRight, CaretTop, ChatDotSquare,
  ChatLineSquare, Checked, CircleCheckFilled, CircleCloseFilled,
  CirclePlusFilled, CloseBold, Cloudy, CoffeeCup, ColdDrink,
  CollectionTag, Comment, Compass, CopyDocument, Cpu, Crop,
  DArrowLeft, DArrowRight, DataAnalysis, DataBoard, DataLine,
  DeleteFilled, DeleteLocation, DishDot, DocumentAdd,
  DocumentChecked, DocumentCopy, DocumentDelete, DocumentRemove,
  Drizzling, EditPen, Eleme, ElemeFilled, Female, FirstAidKit,
  Flag, FolderAdd, FolderChecked, FolderDelete, FolderOpened,
  FolderRemove, Football, ForkSpoon, Fries, Goblet, GobletFull,
  GobletSquareFull, GoldMedal, HotWater, IceDrink, Iphone,
  KnifeFork, Lightning, LocationFilled, LocationInformation,
  Lollipop, MagicStick, Magnet, Male, MapLocation, Medal, Memo,
  MessageBox, Mic, Microphone, MilkTea, Minus, Moon, MoonNight,
  MostlyCloudy, Mouse, Mute, NoSmoking, Odometer, Open,
  Paperclip, PartlyCloudy, PhoneFilled, PictureFilled,
  PictureRounded, Postcard, Pouring, PriceTag, Printer,
  QuartzWatch, RefreshLeft, Refrigerator, Remove,
  RemoveFilled, ScaleToOriginal, Scissor, SemiSelect, Service,
  Ship, Smoking, SoldOut, UploadFilled, VideoCameraFilled
} from '@element-plus/icons-vue'
import { ElMessage, ElMessageBox } from 'element-plus'
import type { FormInstance, TreeInstance } from 'element-plus'

// 在 script setup 开头添加类型定义
interface MenuItem {
  id: number | string
  type: 'menu' | 'button' | 'api'
  title: string
  permission: string
  path?: string
  icon?: string
  sort: number
  parentId?: number | string | null
  children?: MenuItem[]
  status?: 'enabled' | 'disabled'
  description?: string
  component?: string
  isCache?: boolean
  isVisible?: boolean
}

// 菜单树相关
const menuTreeRef = ref<TreeInstance>()
const menuList = ref<MenuItem[]>([])
const currentNode = ref<any>(null)
const defaultProps = {
  children: 'children',
  label: 'title'
}

// 表单相关
const formRef = ref<FormInstance>()
const formData = reactive<{
  id: string | number
  type: 'menu' | 'button' | 'api'
  title: string
  permission: string
  path: string
  icon: string
  sort: number
  parentId?: number | string | null
  parentTitle?: string
  status: 'enabled' | 'disabled'
  description: string
  component: string
  isCache: boolean
  isVisible: boolean
}>({
  id: '',
  type: 'menu',
  title: '',
  permission: '',
  path: '',
  icon: '',
  sort: 0,
  parentId: null,
  parentTitle: '',
  status: 'enabled',
  description: '',
  component: '',
  isCache: true,
  isVisible: true
})

// 表单校验规则
const formRules = {
  type: [{ required: true, message: '请选择菜单类型', trigger: 'change' }],
  title: [{ required: true, message: '请输入菜单名称', trigger: 'blur' }],
  permission: [
    { required: true, message: '请输入权限标识', trigger: 'blur' },
    { pattern: /^[a-z]+:[a-z]+(:?[a-z]+)?$/, message: '格式：模块:操作，如：user:create', trigger: 'blur' }
  ],
  path: [
    { required: true, message: '请输入路由路径', trigger: 'blur' },
    { pattern: /^\//, message: '路由路径必须以 / 开头', trigger: 'blur' }
  ],
  sort: [{ required: true, message: '请输入排序号', trigger: 'blur' }],
  parentId: [{ required: true, message: '请选择上级菜单', trigger: 'change' }],
  component: [
    { required: true, message: '请输入组件路径', trigger: 'blur' },
    { pattern: /^[A-Z]/, message: '组件名称需以大写字母开头', trigger: 'blur' }
  ],
  description: [
    { max: 200, message: '描述最多200个字符', trigger: 'blur' }
  ]
}

// 搜索相关
const searchKey = ref('')

// 获取菜单列表
const getMenuList = () => {
  // 模拟数据
  menuList.value = [
    {
      id: 1,
      title: '系统管理',
      type: 'menu',
      icon: 'Setting',
      path: '/system',
      permission: 'system',
      sort: 1,
      children: [
        {
          id: 2,
          title: '用户管理',
          type: 'menu',
          icon: 'User',
          path: '/system/user',
          permission: 'system:user',
          sort: 1
        },
        {
          id: 3,
          title: '新增用户',
          type: 'button',
          permission: 'system:user:create',
          sort: 2
        }
      ]
    }
  ]
}

// 获取菜单类型标签样式
const getMenuTagType = (type: string) => {
  const typeMap: Record<string, string> = {
    menu: 'success',
    button: 'warning',
    api: 'info'
  }
  return typeMap[type] || 'info'
}

// 获取菜单类型名称
const getMenuTypeName = (type: string) => {
  const typeMap: Record<string, string> = {
    menu: '菜单',
    button: '按钮',
    api: '接口'
  }
  return typeMap[type] || '未知'
}

// 添加处理上级菜单选择的方法
const selectedParentNode = ref<MenuItem | null>(null)

const handleParentSelect = (data: MenuItem) => {
  selectedParentNode.value = data
}

const confirmParentSelect = () => {
  if (selectedParentNode.value) {
    formData.parentId = selectedParentNode.value.id
    formData.parentTitle = selectedParentNode.value.title
  }
  parentMenuDialogVisible.value = false
}

// 修改 handleAddMenu 方法
const handleAddMenu = () => {
  // 创建一个新的空节点作为当前节点，这样右侧会显示表单
  currentNode.value = {
    id: '',
    type: 'menu',
    title: '',
    permission: '',
    path: '',
    icon: '',
    sort: 0,
    parentId: null
  }
  
  // 重置表单数据
  Object.assign(formData, {
    id: '',
    type: 'menu',
    title: '',
    permission: '',
    path: '',
    icon: '',
    sort: 0,
    parentId: null,
    parentTitle: ''
  })
}

// 修改 handleNodeClick 方法
const handleNodeClick = (data: MenuItem) => {
  currentNode.value = data
  // 获取父节点信息
  const parentNode = findParentNode(menuList.value, data.id)
  Object.assign(formData, {
    ...data,
    parentTitle: parentNode?.title || ''
  })
}

// 添加查找父节点的方法
const findParentNode = (list: MenuItem[], childId: number | string): MenuItem | null => {
  for (const item of list) {
    if (item.children?.some(child => child.id === childId)) {
      return item
    }
    if (item.children) {
      const found = findParentNode(item.children, childId)
      if (found) return found
    }
  }
  return null
}

// 修改 handleAddChild 方法
const handleAddChild = (data: MenuItem) => {
  // 创建一个新的节点作为当前节点
  currentNode.value = {
    id: '',
    type: 'menu',
    title: '',
    permission: '',
    path: '',
    icon: '',
    sort: 0,
    parentId: data.id
  }
  
  // 重置表单数据并设置父节点
  Object.assign(formData, {
    id: '',
    type: 'menu',
    title: '',
    permission: '',
    path: '',
    icon: '',
    sort: 0,
    parentId: data.id,
    parentTitle: data.title
  })
}

// 处理编辑菜单
const handleEdit = (data: any) => {
  currentNode.value = data
  Object.assign(formData, data)
}

// 处理删除菜单
const handleDelete = async (data: any) => {
  try {
    await ElMessageBox.confirm('确定要删除该菜单吗？', '提示', {
      type: 'warning'
    })
    // TODO: 调用删除接口
    ElMessage.success('删除成功')
    getMenuList()
  } catch (error) {
    console.error(error)
  }
}

// 添加图标选择对话框的控制变量
const iconSelectVisible = ref(false)

// 定义所有可用的图标列表
const iconList = [
  { name: 'Menu', component: Menu },
  { name: 'Setting', component: Setting },
  { name: 'User', component: User },
  { name: 'UserFilled', component: UserFilled },
  { name: 'Lock', component: Lock },
  { name: 'Unlock', component: Unlock },
  { name: 'Key', component: Key },
  { name: 'Monitor', component: Monitor },
  { name: 'Tools', component: Tools },
  { name: 'Bell', component: Bell },
  { name: 'Message', component: Message },
  { name: 'Link', component: Link },
  { name: 'Position', component: Position },
  { name: 'List', component: List },
  { name: 'Grid', component: Grid },
  { name: 'Operation', component: Operation },
  { name: 'Tickets', component: Tickets },
  { name: 'TrendCharts', component: TrendCharts },
  { name: 'Histogram', component: Histogram },
  { name: 'PieChart', component: PieChart },
  { name: 'Document', component: Document },
  { name: 'Folder', component: Folder },
  { name: 'Box', component: Box },
  { name: 'Files', component: Files },
  { name: 'Edit', component: Edit },
  { name: 'Delete', component: Delete },
  { name: 'Plus', component: Plus },
  { name: 'Search', component: Search },
  { name: 'Close', component: Close },
  { name: 'Warning', component: Warning },
  { name: 'CircleClose', component: CircleClose },
  { name: 'CircleCheck', component: CircleCheck },
  { name: 'Check', component: Check },
  { name: 'Refresh', component: Refresh },
  { name: 'RefreshRight', component: RefreshRight },
  { name: 'House', component: House },
  { name: 'HomeFilled', component: HomeFilled },
  { name: 'School', component: School },
  { name: 'Office', component: OfficeBuilding },
  { name: 'Camera', component: Camera },
  { name: 'Picture', component: Picture },
  { name: 'Upload', component: Upload },
  { name: 'Download', component: Download },
  { name: 'Location', component: Location },
  { name: 'Share', component: Share },
  { name: 'Star', component: Star },
  { name: 'StarFilled', component: StarFilled },
  { name: 'Calendar', component: Calendar },
  { name: 'Timer', component: Timer },
  { name: 'Clock', component: Clock },
  { name: 'Stopwatch', component: Stopwatch },
  { name: 'MoreFilled', component: MoreFilled },
  { name: 'ArrowDown', component: ArrowDown },
  { name: 'ArrowUp', component: ArrowUp },
  { name: 'ArrowLeft', component: ArrowLeft },
  { name: 'ArrowRight', component: ArrowRight },
  { name: 'Back', component: Back },
  { name: 'Right', component: Right },
  { name: 'Top', component: Top },
  { name: 'Bottom', component: Bottom },
  { name: 'DCaret', component: DCaret },
  { name: 'InfoFilled', component: InfoFilled },
  { name: 'SuccessFilled', component: SuccessFilled },
  { name: 'Loading', component: Loading },
  { name: 'Failed', component: Failed },
  { name: 'Aim', component: Aim },
  { name: 'Help', component: Help },
  { name: 'Pointer', component: Pointer },
  { name: 'Rank', component: Rank },
  { name: 'Sort', component: Sort },
  { name: 'SortDown', component: SortDown },
  { name: 'SortUp', component: SortUp },
  { name: 'Trophy', component: Trophy },
  { name: 'Expand', component: Expand },
  { name: 'Fold', component: Fold },
  { name: 'FullScreen', component: FullScreen },
  { name: 'ZoomIn', component: ZoomIn },
  { name: 'ZoomOut', component: ZoomOut },
  { name: 'Opportunity', component: Opportunity },
  { name: 'Shop', component: Shop },
  { name: 'ShoppingTrolley', component: ShoppingTrolley },
  { name: 'Soccer', component: Soccer },
  { name: 'Sunny', component: Sunny },
  { name: 'Sunrise', component: Sunrise },
  { name: 'Sunset', component: Sunset },
  { name: 'TakeawayBox', component: TakeawayBox },
  { name: 'Ticket', component: Ticket },
  { name: 'TopLeft', component: TopLeft },
  { name: 'TopRight', component: TopRight },
  { name: 'TurnOff', component: TurnOff },
  { name: 'Van', component: Van },
  { name: 'VideoPause', component: VideoPause },
  { name: 'VideoPlay', component: VideoPlay },
  { name: 'WarnTriangleFilled', component: WarnTriangleFilled },
  { name: 'WindPower', component: WindPower },
  { name: 'Bowl', component: Bowl },
  { name: 'Brush', component: Brush },
  { name: 'BrushFilled', component: BrushFilled },
  { name: 'CaretBottom', component: CaretBottom },
  { name: 'CaretLeft', component: CaretLeft },
  { name: 'CaretRight', component: CaretRight },
  { name: 'CaretTop', component: CaretTop },
  { name: 'ChatDotSquare', component: ChatDotSquare },
  { name: 'ChatLineSquare', component: ChatLineSquare },
  { name: 'Checked', component: Checked },
  { name: 'CircleCheckFilled', component: CircleCheckFilled },
  { name: 'CircleCloseFilled', component: CircleCloseFilled },
  { name: 'CirclePlusFilled', component: CirclePlusFilled },
  { name: 'CloseBold', component: CloseBold },
  { name: 'Cloudy', component: Cloudy },
  { name: 'CoffeeCup', component: CoffeeCup },
  { name: 'ColdDrink', component: ColdDrink },
  { name: 'CollectionTag', component: CollectionTag },
  { name: 'Comment', component: Comment },
  { name: 'Compass', component: Compass },
  { name: 'CopyDocument', component: CopyDocument },
  { name: 'Cpu', component: Cpu },
  { name: 'Crop', component: Crop },
  { name: 'DArrowLeft', component: DArrowLeft },
  { name: 'DArrowRight', component: DArrowRight },
  { name: 'DataAnalysis', component: DataAnalysis },
  { name: 'DataBoard', component: DataBoard },
  { name: 'DataLine', component: DataLine },
  { name: 'DeleteFilled', component: DeleteFilled },
  { name: 'DeleteLocation', component: DeleteLocation },
  { name: 'DishDot', component: DishDot },
  { name: 'DocumentAdd', component: DocumentAdd },
  { name: 'DocumentChecked', component: DocumentChecked },
  { name: 'DocumentCopy', component: DocumentCopy },
  { name: 'DocumentDelete', component: DocumentDelete },
  { name: 'DocumentRemove', component: DocumentRemove },
  { name: 'Drizzling', component: Drizzling },
  { name: 'EditPen', component: EditPen },
  { name: 'Eleme', component: Eleme },
  { name: 'ElemeFilled', component: ElemeFilled },
  { name: 'Female', component: Female },
  { name: 'FirstAidKit', component: FirstAidKit },
  { name: 'Flag', component: Flag },
  { name: 'FolderAdd', component: FolderAdd },
  { name: 'FolderChecked', component: FolderChecked },
  { name: 'FolderDelete', component: FolderDelete },
  { name: 'FolderOpened', component: FolderOpened },
  { name: 'FolderRemove', component: FolderRemove },
  { name: 'Football', component: Football },
  { name: 'ForkSpoon', component: ForkSpoon },
  { name: 'Fries', component: Fries },
  { name: 'Goblet', component: Goblet },
  { name: 'GobletFull', component: GobletFull },
  { name: 'GobletSquareFull', component: GobletSquareFull },
  { name: 'GoldMedal', component: GoldMedal },
  { name: 'HotWater', component: HotWater },
  { name: 'IceDrink', component: IceDrink },
  { name: 'Iphone', component: Iphone },
  { name: 'KnifeFork', component: KnifeFork },
  { name: 'Lightning', component: Lightning },
  { name: 'LocationFilled', component: LocationFilled },
  { name: 'LocationInformation', component: LocationInformation },
  { name: 'Lollipop', component: Lollipop },
  { name: 'MagicStick', component: MagicStick },
  { name: 'Magnet', component: Magnet },
  { name: 'Male', component: Male },
  { name: 'MapLocation', component: MapLocation },
  { name: 'Medal', component: Medal },
  { name: 'Memo', component: Memo },
  { name: 'MessageBox', component: MessageBox },
  { name: 'Mic', component: Mic },
  { name: 'Microphone', component: Microphone },
  { name: 'MilkTea', component: MilkTea },
  { name: 'Minus', component: Minus },
  { name: 'Moon', component: Moon },
  { name: 'MoonNight', component: MoonNight },
  { name: 'MostlyCloudy', component: MostlyCloudy },
  { name: 'Mouse', component: Mouse },
  { name: 'Mute', component: Mute },
  { name: 'NoSmoking', component: NoSmoking },
  { name: 'Odometer', component: Odometer },
  { name: 'Open', component: Open },
  { name: 'Paperclip', component: Paperclip },
  { name: 'PartlyCloudy', component: PartlyCloudy },
  { name: 'PhoneFilled', component: PhoneFilled },
  { name: 'PictureFilled', component: PictureFilled },
  { name: 'PictureRounded', component: PictureRounded },
  { name: 'Postcard', component: Postcard },
  { name: 'Pouring', component: Pouring },
  { name: 'PriceTag', component: PriceTag },
  { name: 'Printer', component: Printer },
  { name: 'QuartzWatch', component: QuartzWatch },
  { name: 'RefreshLeft', component: RefreshLeft },
  { name: 'Refrigerator', component: Refrigerator },
  { name: 'Remove', component: Remove },
  { name: 'RemoveFilled', component: RemoveFilled },
  { name: 'ScaleToOriginal', component: ScaleToOriginal },
  { name: 'Scissor', component: Scissor },
  { name: 'SemiSelect', component: SemiSelect },
  { name: 'Service', component: Service },
  { name: 'Ship', component: Ship },
  { name: 'Smoking', component: Smoking },
  { name: 'SoldOut', component: SoldOut },
  { name: 'UploadFilled', component: UploadFilled },
  { name: 'VideoCameraFilled', component: VideoCameraFilled }
]

// 添加选择图标的方法
const handleIconSelect = (iconName: string) => {
  formData.icon = iconName
  iconSelectVisible.value = false
}

// 添加图标搜索功能
const iconSearchKey = ref('')
const filteredIconList = computed(() => {
  if (!iconSearchKey.value) return iconList
  return iconList.filter(icon => 
    icon.name.toLowerCase().includes(iconSearchKey.value.toLowerCase())
  )
})

// 处理表单提交
const handleSubmit = async () => {
  if (!formRef.value) return
  try {
    await formRef.value.validate()
    
    // 构造保存的数据
    const saveData: MenuItem = {
      ...formData,
      // 如果是新增，生成临时 ID（实际项目中应该由后端生成）
      id: formData.id || Date.now()
    }
    
    if (formData.id) {
      // 更新现有节点
      updateTreeNode(menuList.value, saveData)
    } else {
      // 新增节点
      if (formData.parentId) {
        // 添加子节点
        addChildNode(menuList.value, formData.parentId, saveData)
      } else {
        // 添加根节点
        menuList.value.push(saveData)
      }
    }
    
    ElMessage.success('保存成功')
    currentNode.value = null
    resetForm()
  } catch (error) {
    console.error(error)
  }
}

// 重置表单
const resetForm = () => {
  if (!formRef.value) return
  formRef.value.resetFields()
}

// 过滤节点方法
const filterNode = (value: string, data: any) => {
  if (!value) return true
  return data.title.toLowerCase().includes(value.toLowerCase())
}

// 监听搜索关键字变化
watch(searchKey, (val) => {
  menuTreeRef.value?.filter(val)
})

// 添加更新树节点的方法
const updateTreeNode = (list: MenuItem[], newNode: MenuItem): boolean => {
  for (let i = 0; i < list.length; i++) {
    if (list[i].id === newNode.id) {
      list[i] = { ...list[i], ...newNode }
      return true
    }
    if (list[i].children && list[i].children.length > 0) {
      if (updateTreeNode(list[i].children, newNode)) {
        return true
      }
    }
  }
  return false
}

// 添加子节点的方法
const addChildNode = (list: MenuItem[], parentId: number | string, newNode: MenuItem): boolean => {
  for (let i = 0; i < list.length; i++) {
    if (list[i].id === parentId) {
      if (!list[i].children) {
        list[i].children = []
      }
      list[i].children.push(newNode)
      return true
    }
    if (list[i].children && list[i].children.length > 0) {
      if (addChildNode(list[i].children, parentId, newNode)) {
        return true
      }
    }
  }
  return false
}

// 添加选择上级菜单的对话框控制
const parentMenuDialogVisible = ref(false)

// 添加获取扁平化菜单列表的方法
const getFlatMenuList = (list: MenuItem[] = menuList.value, result: MenuItem[] = []): MenuItem[] => {
  list.forEach(item => {
    result.push(item)
    if (item.children) {
      getFlatMenuList(item.children, result)
    }
  })
  return result
}

// 打开选择上级菜单的对话框
const openParentMenuDialog = () => {
  parentMenuDialogVisible.value = true
}

// 添加导入导出功能
const handleExport = () => {
  const data = JSON.stringify(menuList.value, null, 2)
  const blob = new Blob([data], { type: 'application/json' })
  const url = URL.createObjectURL(blob)
  const link = document.createElement('a')
  link.href = url
  link.download = 'menu-config.json'
  link.click()
  URL.revokeObjectURL(url)
}

// 添加拖拽排序功能
const handleDrop = (draggingNode: any, dropNode: any, dropType: 'before' | 'after' | 'inner') => {
  const draggingData = draggingNode.data
  const dropData = dropNode.data
  
  // 更新排序逻辑
  if (dropType === 'inner') {
    draggingData.parentId = dropData.id
  } else {
    draggingData.parentId = dropData.parentId
  }
  
  // 更新排序号
  updateNodeSort(menuList.value)
}

// 更新节点排序
const updateNodeSort = (nodes: MenuItem[], startSort = 0): number => {
  nodes.forEach((node, index) => {
    node.sort = startSort + index
    if (node.children?.length) {
      updateNodeSort(node.children, node.sort * 100)
    }
  })
  return nodes.length
}

// 添加展开/折叠功能
const handleExpandAll = () => {
  const tree = menuTreeRef.value
  if (tree) {
    const nodes = tree.store.nodesMap
    for (const key in nodes) {
      nodes[key].expanded = true
    }
  }
}

const handleCollapseAll = () => {
  const tree = menuTreeRef.value
  if (tree) {
    const nodes = tree.store.nodesMap
    for (const key in nodes) {
      nodes[key].expanded = false
    }
  }
}

// 添加导入功能
const handleImport = () => {
  const input = document.createElement('input')
  input.type = 'file'
  input.accept = '.json'
  input.onchange = (e: Event) => {
    const file = (e.target as HTMLInputElement).files?.[0]
    if (file) {
      const reader = new FileReader()
      reader.onload = (e) => {
        try {
          const data = JSON.parse(e.target?.result as string)
          menuList.value = data
          ElMessage.success('导入成功')
        } catch (error) {
          ElMessage.error('导入失败，请检查文件格式')
        }
      }
      reader.readAsText(file)
    }
  }
  input.click()
}

// 初始化
onMounted(() => {
  getMenuList()
})
</script>

<style lang="scss" scoped>
.permission-manage {
  display: flex;
  gap: 24px;
  height: 100%;
  padding: 20px;
  background-color: #f5f7fa;
  animation: slide-in 0.3s ease-out;
  
  @keyframes slide-in {
    from {
      opacity: 0;
      transform: translateY(20px);
    }
    to {
      opacity: 1;
      transform: translateY(0);
    }
  }
  
  .menu-tree-card,
  .menu-form-card {
    transition: all 0.3s cubic-bezier(0.4, 0, 0.2, 1);
    position: relative;
    overflow: hidden;
    
    &::before {
      content: '';
      position: absolute;
      top: 0;
      left: 0;
      right: 0;
      height: 3px;
      background: linear-gradient(90deg, var(--el-color-primary), var(--el-color-success));
      transform: scaleX(0);
      transition: transform 0.3s ease;
      transform-origin: left;
    }
    
    &:hover::before {
      transform: scaleX(1);
    }
    
    &:hover {
      transform: translateY(-4px);
      box-shadow: 0 8px 24px rgba(0, 0, 0, 0.12);
    }
  }
  
  .menu-tree-card {
    width: 360px;
    height: calc(100vh - 160px);
    background: #fff;
    border-radius: 12px;
    box-shadow: 0 2px 12px 0 rgba(0, 0, 0, 0.05);
    
    .card-header {
      padding: 16px 20px;
      border-bottom: 1px solid #ebeef5;
      background: #fafafa;
      border-radius: 12px 12px 0 0;
      
      .title {
        font-size: 18px;
        color: #303133;
      }
    }
    
    .tree-search {
      margin: 16px 20px;
      
      :deep(.el-input__wrapper) {
        border-radius: 8px;
      }
    }
    
    :deep(.el-tree) {
      .el-tree-node__content {
        height: 44px;
        margin: 4px 0;
        border-radius: 8px;
        
        &:hover {
          background-color: #f0f7ff;
        }
        
        &.is-current {
          background-color: #e6f2ff;
          
          .node-content {
            .el-icon {
              color: var(--el-color-primary);
            }
            
            .label {
              color: var(--el-color-primary);
              font-weight: 500;
            }
          }
        }
      }
    }
    
    .custom-tree-node {
      flex: 1;
      display: flex;
      align-items: center;
      justify-content: space-between;
      padding: 0 8px;
      
      .node-content {
        display: flex;
        align-items: center;
        gap: 8px;
        
        .el-icon {
          font-size: 16px;
          color: var(--el-text-color-secondary);
          transition: all 0.3s ease;
        }
        
        .label {
          font-size: 14px;
          transition: color 0.3s ease;
        }
        
        .el-tag {
          margin-left: 8px;
          font-size: 12px;
          font-weight: 500;
          transition: all 0.3s ease;
          position: relative;
          overflow: hidden;
          
          &::after {
            content: '';
            position: absolute;
            top: -50%;
            left: -50%;
            width: 200%;
            height: 200%;
            background: linear-gradient(
              transparent,
              rgba(255, 255, 255, 0.3),
              transparent
            );
            transform: rotate(45deg);
            animation: shine 2s infinite;
          }
        }
      }
      
      .node-actions {
        opacity: 0;
        transition: opacity 0.3s ease;
        
        .el-button {
          padding: 4px;
          transition: all 0.3s ease;
          
          .el-icon {
            font-size: 14px;
          }
          
          &:hover {
            background-color: var(--el-color-primary-light-8);
          }
        }
      }
      
      &:hover .node-actions {
        opacity: 1;
      }
    }
  }
  
  .menu-form-card {
    flex: 1;
    background: #fff;
    border-radius: 12px;
    box-shadow: 0 2px 12px 0 rgba(0, 0, 0, 0.05);
    
    .card-header {
      padding: 16px 24px;
      background: #fafafa;
      border-radius: 12px 12px 0 0;
      
      .title {
        font-size: 18px;
        color: #303133;
      }
    }
    
    .toolbar {
      padding: 16px 24px;
      display: flex;
      gap: 16px;
      justify-content: flex-end;
      border-bottom: 1px solid #ebeef5;
      background: linear-gradient(to right, #fafafa, #f5f7fa);
      
      .el-button {
        transition: all 0.3s ease;
        
        &:hover {
          transform: translateY(-2px);
          box-shadow: 0 4px 12px rgba(0, 0, 0, 0.1);
        }
        
        .el-icon {
          transition: transform 0.3s ease;
        }
        
        &:hover .el-icon {
          transform: scale(1.2);
        }
      }
    }
    
    :deep(.el-form) {
      padding: 24px;
      
      .el-form-item {
        position: relative;
        
        &::after {
          content: '';
          position: absolute;
          bottom: 0;
          left: 0;
          width: 100%;
          height: 2px;
          background: linear-gradient(90deg, var(--el-color-primary), transparent);
          transform: scaleX(0);
          transition: transform 0.3s ease;
          transform-origin: left;
        }
        
        &:hover::after {
          transform: scaleX(1);
        }
        
        .el-form-item__label {
          background: linear-gradient(90deg, var(--el-color-primary), #606266);
          -webkit-background-clip: text;
          -webkit-text-fill-color: transparent;
          font-weight: 500;
        }
      }
    }
    
    .empty-tip {
      display: flex;
      justify-content: center;
      align-items: center;
      height: 400px;
      color: var(--el-text-color-secondary);
      
      :deep(.el-empty__description) {
        margin-top: 16px;
        font-size: 14px;
      }
    }
  }
}

// 添加对话框动画
:deep(.el-dialog) {
  border-radius: 8px;
  overflow: hidden;
  
  .el-dialog__header {
    margin: 0;
    padding: 16px 20px;
    border-bottom: 1px solid var(--el-border-color-lighter);
    
    .el-dialog__title {
      font-size: 16px;
      font-weight: 600;
    }
  }
  
  .el-dialog__body {
    padding: 24px;
  }
  
  .el-dialog__footer {
    padding: 16px 20px;
    border-top: 1px solid var(--el-border-color-lighter);
  }
}

// 添加过渡动画
.v-enter-active,
.v-leave-active {
  transition: opacity 0.3s ease;
}

.v-enter-from,
.v-leave-to {
  opacity: 0;
}

// 修改图标选择弹出层样式
.icon-select-popover {
  padding: 0 !important;
  
  .icon-select-container {
    .icon-search {
      padding: 12px;
      border-bottom: 1px solid var(--el-border-color-lighter);
    }
    
    .icon-grid {
      padding: 12px;
      height: 300px;
      overflow-y: auto;
      overflow-x: hidden;
      display: grid;
      grid-template-columns: repeat(6, 1fr);
      gap: 8px;
      
      &::-webkit-scrollbar {
        width: 6px;
        height: 0;
      }
      
      &::-webkit-scrollbar-thumb {
        background: var(--el-border-color-lighter);
        border-radius: 3px;
      }
      
      &::-webkit-scrollbar-track {
        background: transparent;
      }
      
      .icon-item {
        width: 100%;
        min-width: 0;
        display: flex;
        flex-direction: column;
        align-items: center;
        justify-content: center;
        gap: 4px;
        padding: 8px 4px;
        border: 1px solid var(--el-border-color-lighter);
        border-radius: 4px;
        cursor: pointer;
        transition: all 0.3s cubic-bezier(0.4, 0, 0.2, 1);
        
        .el-icon {
          font-size: 20px;
          color: var(--el-text-color-primary);
        }
        
        .icon-name {
          font-size: 12px;
          color: var(--el-text-color-secondary);
          text-align: center;
          width: 100%;
          overflow: hidden;
          text-overflow: ellipsis;
          white-space: nowrap;
          padding: 0 2px;
        }
        
        &:hover {
          transform: scale(1.1);
          z-index: 1;
          box-shadow: 0 4px 12px rgba(0, 0, 0, 0.1);
          
          .el-icon {
            color: var(--el-color-primary);
          }
          
          .icon-name {
            color: var(--el-color-primary);
          }
        }
      }
    }
  }
}

// 修改输入框中图标的样式
.el-form-item {
  :deep(.el-input) {
    .el-input__prefix {
      .el-icon {
        font-size: 16px;
        margin-right: 8px;
      }
    }
  }
}

// 响应式布局优化
@media screen and (max-width: 1400px) {
  .icon-select-popover {
    :deep(.el-dialog__body) {
      .icon-select-container {
        grid-template-columns: repeat(5, 1fr);
      }
    }
  }
}

@media screen and (max-width: 1200px) {
  .icon-select-popover {
    :deep(.el-dialog__body) {
      .icon-select-container {
        grid-template-columns: repeat(4, 1fr);
      }
    }
  }
}

@media screen and (max-width: 768px) {
  .icon-select-popover {
    :deep(.el-dialog__body) {
      .icon-select-container {
        grid-template-columns: repeat(3, 1fr);
      }
    }
  }
}

// 修改上级菜单选择对话框的样式
:deep(.el-dialog) {
  .el-tree {
    padding: 12px;
    
    .el-tree-node {
      &.is-current {
        > .el-tree-node__content {
          background-color: var(--el-color-primary-light-8);
          color: var(--el-color-primary);
          font-weight: 500;
          
          .el-icon {
            color: var(--el-color-primary);
          }
        }
      }
      
      .el-tree-node__content {
        height: 40px;
        border-radius: 4px;
        margin-bottom: 4px;
        transition: all 0.3s ease;
        
        &:hover {
          background-color: var(--el-color-primary-light-9);
        }
        
        .custom-tree-node {
          flex: 1;
          display: flex;
          align-items: center;
          gap: 8px;
          padding: 0 8px;
          
          .node-content {
            display: flex;
            align-items: center;
            gap: 8px;
            
            .el-icon {
              font-size: 16px;
              color: var(--el-text-color-secondary);
              transition: color 0.3s ease;
            }
            
            .label {
              font-size: 14px;
              transition: all 0.3s ease;
            }
          }
        }
      }
    }
  }
  
  .el-dialog__footer {
    border-top: 1px solid var(--el-border-color-lighter);
    padding: 12px 20px;
    
    .el-button {
      padding: 8px 20px;
      min-width: 80px;
      
      &--primary {
        font-weight: 500;
      }
    }
  }
}

@keyframes shine {
  0% {
    left: -50%;
  }
  100% {
    left: 100%;
  }
}

@keyframes ripple {
  0% {
    transform: scale(0, 0);
    opacity: 0.5;
  }
  100% {
    transform: scale(40, 40);
    opacity: 0;
  }
}
</style> 